package com.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class SumJaxWsProcess {
	static final String JAXWS_RI_RUNTIME = "E:/workspace/jaxws-tomcat-spring/src/main/webapp/WEB-INF/sun-jaxws.xml";

	public static void main(String[] args) throws Exception {
		// 创建解析器
		SAXReader reader = new SAXReader();
		org.dom4j.Document document = reader.read(new File(JAXWS_RI_RUNTIME));
		org.dom4j.Element root = document.getRootElement();

		List<Element> list = root.elements();

		for (Element e : list) {
			// 获取属性值
			String name = e.attributeValue("name");
			String implementation = e.attributeValue("implementation");
			String urlPattern = e.attributeValue("url-pattern");

			System.out.println(implementation + name + urlPattern);
		}

		Element product = root.addElement("product");
		product.addAttribute("name", "name");
		product.addAttribute("implementation", "implementation");
		product.addAttribute("url-pattern", "url-pattern");

		writeXml(document, JAXWS_RI_RUNTIME);
	}

	public static void writeXml(Document document, String filePath) throws IOException {
		File xmlFile = new File(filePath);
		XMLWriter writer = null;
		try {
			if (xmlFile.exists())
				xmlFile.delete();
			writer = new XMLWriter(new FileOutputStream(xmlFile), OutputFormat.createPrettyPrint());
			writer.write(document);
			writer.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null)
				writer.close();
		}
	}
}
